package cn.ithers.blog.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.ithers.blog.pojo.User;
import cn.ithers.blog.service.IUserService;
import cn.ithers.blog.utils.Constants;
import cn.ithers.blog.utils.CookieUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: zhanghuan
 * @date: 2020/9/24 15:07
 * @description:
 */
@Slf4j
@Service("permission")
public class PermissionService {

    @Autowired
    private IUserService userService;

    public boolean admin() {
        //拿到request和response
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String tokenKey = CookieUtils.getCookie(request, Constants.User.COOKIE_TOKEN_KEY);

        //没有令牌的key,没有登录，不用往下执行
        if (StrUtil.isEmpty(tokenKey)) {
            log.info("您没有登录");
            return false;
        }
        User user = userService.checkUser();
        if (user == null) {
            log.info("您不是管理员");
            return false;
        }
        if (Constants.User.ROLE_ADMIN.equals(user.getRoles())) {
            //管理员
            return true;
        }
        return false;

    }
}
